package com.xiaotao.controller;

import com.xiaotao.entity.Room;
import com.xiaotao.service.WebSocketService;
import com.xiaotao.util.JwtUtil;
import com.xiaotao.util.ResponseEnum;
import com.xiaotao.util.ResponseUtil;
import io.minio.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@Slf4j
@RequestMapping("/api/room")
public class    RoomController {
    @Autowired
    private WebSocketService webSocketService;
    @GetMapping("/userRooms")
    public ResponseUtil getUserJoinedRooms(HttpServletRequest request) {
        String userId = UserToken(request);
        if (userId == null) {
            log.warn("获取房间列表失败：Token无效或解析失败");
            return ResponseUtil.get(ResponseEnum.FAIL);
        }
        List<Map<String, Object>> userRooms = new ArrayList<>();
        for (Room room : WebSocketService.getRoomMap().values()) {
            if (room.getUserMap().containsKey(userId)) {
                userRooms.add(buildRoomInfo(room, userId));
            }
        }
        log.info("用户[{}]查询到{}个聊天室", userId, userRooms.size());
        return ResponseUtil.get(ResponseEnum.OK, userRooms);
    }
    private String UserToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null || token.trim().isEmpty()) {
            log.warn("Token不存在：请求头未携带token");
            return null;
        }
        try {
            Integer userIdInt = JwtUtil.getUserId(token);
            return userIdInt.toString(); // 转为String，与room.getUserMap()的key类型匹配
        } catch (Exception e) {
            log.error("Token解析失败：{}", e.getMessage());
            return null;
        }
    }
    private Map<String, Object> buildRoomInfo(Room room, String currentUserId) {
        Map<String, Object> roomInfo = new HashMap<>(4);
        roomInfo.put("roomId", room.getRoomId());         // 房间ID
        roomInfo.put("roomOwner", room.getOwnerId());     // 房主ID
        roomInfo.put("onlineCount", room.getUserMap().size()); // 在线人数
        roomInfo.put("isOwner", currentUserId.equals(room.getOwnerId())); // 是否为房主
        return roomInfo;
    }
    @GetMapping("/exists")
    public ResponseUtil checkRoomExists(@RequestParam String roomId){
        ConcurrentHashMap<String ,Room> roomMap = WebSocketService.getRoomMap();
        if(roomMap.containsKey(roomId)){
            return  ResponseUtil.get(ResponseEnum.OK);
        }else {
            return ResponseUtil.get(ResponseEnum.FAIL);
        }
    }
    @PostMapping("/create")
    public ResponseUtil createRoom(@RequestBody Map<String, String> params, HttpServletRequest request) {
        String roomId = params.get("roomId");
        String userId = params.get("userId");
        if (roomId == null || userId == null) {
            return ResponseUtil.get(ResponseEnum.FAIL);
        }
        if (WebSocketService.getRoomMap().containsKey(roomId)) {
            return ResponseUtil.get(ResponseEnum.FAIL);
        }
        Room newRoom = new Room(roomId, userId, 10);
        WebSocketService.getRoomMap().put(roomId, newRoom);
        log.info("用户[{}]创建聊天室成功，房间号：{}", userId, roomId);
        return ResponseUtil.get(ResponseEnum.OK);
    }
    //私聊
    @PostMapping("/createPrivate")
    public ResponseUtil createPrivateRoom(@RequestBody Map<String, String> params, HttpServletRequest request) {
        String currentUserId = UserToken(request);
        if (currentUserId == null) {
            return ResponseUtil.get(ResponseEnum.NO1);
        }
        String targetUserId = params.get("targetUserId");
        String roomId = params.get("roomId");
        if (targetUserId == null || roomId == null) {
            return ResponseUtil.get(ResponseEnum.NO2);
        }
        if (currentUserId.equals(targetUserId)) {
            return ResponseUtil.get(ResponseEnum.NO3);
        }

        ConcurrentHashMap<String, Room> roomMap = WebSocketService.getRoomMap();
        Room privateRoom = roomMap.get(roomId);
        if (privateRoom == null) {
            privateRoom = new Room(roomId, currentUserId, 2);
            roomMap.put(roomId, privateRoom);
            log.info("用户[{}]与用户[{}]创建私聊房间成功，房间号：{}", currentUserId, targetUserId, roomId);
        } else {
            if (privateRoom.getUserMap().size() >= privateRoom.getMaxUsers()) {
                return ResponseUtil.get(ResponseEnum.NO4);
            }
            log.info("用户[{}]加入已存在的私聊房间[{}]（目标用户：{}）", currentUserId, roomId, targetUserId);
        }
        WebSocketService currentUserWs = getWebSocketServiceByUserId(currentUserId); //
        WebSocketService targetUserWs = getWebSocketServiceByUserId(targetUserId);
        // 校验WebSocketService实例非空
        if (currentUserWs == null) {
            log.error("用户[{}]的WebSocket连接未初始化", currentUserId);
            return ResponseUtil.get(ResponseEnum.FAIL, "当前用户未建立连接");
        }
        privateRoom.getUserMap().putIfAbsent(currentUserId, currentUserWs);
        // 6. 返回成功结果
        return ResponseUtil.get(ResponseEnum.OK, roomId);

    }
    private WebSocketService getWebSocketServiceByUserId(String userId) {

        return new WebSocketService(); // 临时占位，需替换为真实获取逻辑
    }
}